import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { UserInfo } from '@/type/user'

export const useUserStore = defineStore('user', () => {  
  // 用户相关状态
  const token = ref('')
  const userInfo = ref<UserInfo | null>(null)
  const isLoggedIn = computed(() => !!token.value)


  // 用户登录方法
  const loginByPassword = async (params: { username: string; password: string }) => {
    // 这里调用实际登录API
    console.log('密码登录:', params)
    // 模拟登录成功
    token.value = 'mock-token-' + Date.now()
    userInfo.value = {
      id: 1,
      username: params.username,
      phone: '13800138000'
    }
    return Promise.resolve()
  }

  const loginByCode = async (params: { phone: string; code: string }) => {
    // 这里调用实际登录API
    console.log('验证码登录:', params)
    // 模拟登录成功
    token.value = 'mock-token-' + Date.now()
    userInfo.value = {
      id: 1,
      username: 'user_' + params.phone,
      phone: params.phone
    }
    return Promise.resolve()
  }

  const logout = () => {
    token.value = ''
    userInfo.value = null
  }

  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
    token.value = 'mock-token-' + Date.now()
  }

  return { 
  
    setUserInfo,
    
    // 用户相关
    token,
    userInfo,
    isLoggedIn,
    loginByPassword,
    loginByCode,
    logout
  }
},
{
  // @ts-ignore
  unistorage: true, // 开启后对 state 的数据读写都将持久化
},)
